package partlow.yelp.parsers;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import partlow.yelp.datatypes.YelpLocation;

public class LocationParser extends YelpTypeParser<YelpLocation> {

	@Override
	public YelpLocation parse(JSONObject json) throws JSONException {
		YelpLocation obj = new YelpLocation();
		if(json.has("address")) {
			JSONArray addressArray = json.getJSONArray("address");
        	int addressArrayLength = addressArray.length();
        	StringBuilder addressStringBuilder = new StringBuilder();
        	for(int itemIndex = 0; itemIndex < addressArrayLength; itemIndex++) {
        		if(addressStringBuilder.length() > 0)
        			addressStringBuilder.append(" ");
        		addressStringBuilder.append((String)addressArray.get(itemIndex));
        	}
			
			obj.setAddress(addressStringBuilder.toString());
		}
		if(json.has("city"))
        	obj.setCity(json.getString("city"));
		if(json.has("postal_code"))
        	obj.setPostalCode(json.getString("postal_code"));
		if(json.has("state_code"))
        	obj.setStateCode(json.getString("state_code"));
		if(json.has("coordinate")){
            JSONObject coordinate = json.getJSONObject("coordinate");
            obj.setCoordinate(new CoordinateParser().parse(coordinate));
        }
		
		return obj;
	}

}
